package com.lw.leetcode.str.b;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * 791. 自定义字符串排序
 *
 * @Author liw
 * @Date 2021/9/25 13:53
 * @Version 1.0
 */
public class CustomSortString {

    public static void main(String[] args){
        CustomSortString test = new CustomSortString();
        String order = "cba";
        String s = "abcd";
        String s1 = test.customSortString(order, s);
        System.out.println(s1);
    }

    public String customSortString(String order, String s) {
        int[] arr = new int[26];
        int[] arr2 = new int[26];
        char[] orders = order.toCharArray();
        int l = orders.length;
        for (int i = l - 1; i >= 0; i--) {
            arr[orders[i] - 'a'] = i + 26 - l;
        }
        int c = 0;
        for (int i = 0; i < 26; i++) {
            if (arr[i] == 0) {
                arr[i] = c++;
            }
        }
        for (int i = 0; i < 26; i++) {
            arr2[arr[i]] = i;
        }
        int length = s.length();
        int[] values = new int[length];
        char[] ss = s.toCharArray();
        for (int i = 0; i < length; i++) {
            values[i] = arr[ss[i] - 'a'];
        }
        Arrays.sort(values);
        char[] sss = new char[length];
        for (int i = 0; i < length; i++) {
            sss[i] = (char) (arr2[values[i] ] + 'a');
        }
        return new String(sss);
    }

}
